﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEngine.U2D;
using UnityEditor.U2D;

/// <summary>
/// 
/// </summary>
public class XEditorSpritePostprocessor : AssetPostprocessor
{
    /// <summary>
    /// 
    /// </summary>
    static string[] prefabDirs = new string[] {
        XDirectory.Icons.ToString(),
    };

    /// <summary>
    /// 
    /// </summary>
    public void OnPreprocessTexture()
    {
        string[] preprocessTextrueDir = new string[] {
            XDirectory.UI.ToString(), XDirectory.Icons.ToString()
        };

        bool preprocess = false;
        foreach(string dir in preprocessTextrueDir)
        {
            if (assetPath.Contains(dir))
            {
                preprocess = true;
                break;
            }
        }
        
        if (preprocess)
        {
            TextureImporter imp = (TextureImporter)assetImporter;
            imp.textureType = TextureImporterType.Sprite;
            imp.mipmapEnabled = false;
            imp.maxTextureSize = 1024;
            imp.textureCompression = TextureImporterCompression.Compressed;

            if (string.IsNullOrEmpty(imp.spritePackingTag))
            {
                string path = Path.GetDirectoryName(assetPath);
                string name = Path.GetFileName(path);

                imp.spritePackingTag = name.ToLower();
            }

            if (!string.IsNullOrEmpty(imp.spritePackingTag))
            {
                imp.textureCompression = TextureImporterCompression.Uncompressed;

                TextureImporterPlatformSettings androidTexture = new TextureImporterPlatformSettings();
                androidTexture.overridden = true;
                androidTexture.name = "Android";
                androidTexture.maxTextureSize = 1024;
                androidTexture.format = TextureImporterFormat.ETC_RGB4;
                androidTexture.allowsAlphaSplitting = true;

                imp.SetPlatformTextureSettings(androidTexture);

                TextureImporterPlatformSettings standTexture = new TextureImporterPlatformSettings();
                standTexture.name = "Standalone";
                standTexture.overridden = true;

                if (imp.DoesSourceTextureHaveAlpha())
                {
                    standTexture.format = TextureImporterFormat.RGBA32;
                }
                else
                {
                    GLog.LogError("sprite path: {0} Do not have alpha!", imp.assetPath);
                }

                imp.SetPlatformTextureSettings(standTexture);
            }

            foreach (string dirName in prefabDirs)
            {
                if (assetPath.Contains(dirName))
                {
                    XEditorCoroutineRunner.StartEditorCoroutine(OnGenerateIconPrefab());
                }
            }
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="go"></param>
    /// <param name="path"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    static Object GeneratePrefab(GameObject go, string path, string name)
    {
        string fullpath = path + "/" + name + ".prefab";

        GameObject prefab = PrefabUtility.SaveAsPrefabAsset(go, fullpath);
        GameObject.DestroyImmediate(go);

        Debug.Log("fbx postprocess auto generate prefab : <color=red>" + fullpath + "</color>");

        return prefab;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    IEnumerator OnGenerateIconPrefab()
    {
        string name = Path.GetFileNameWithoutExtension(assetPath);
        yield return null;

        string fileName = assetPath.Replace(XDirectory.Art.ToString(), 
            XDirectory.Resources.ToString());

#if UNITY_2019_1_OR_NEWER
        string filePath = Path.GetDirectoryName(fileName);

        string spriteAtlasFile = Path.ChangeExtension(filePath, typeof(SpriteAtlas).Name.ToLower());
        SpriteAtlas spriteAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(spriteAtlasFile);
        if (!spriteAtlas)
        {
            spriteAtlas = new SpriteAtlas();
            AssetDatabase.CreateAsset(spriteAtlas, spriteAtlasFile);
        }
        yield return null;

        Object[] packables = spriteAtlas.GetPackables();
        SpriteAtlasExtensions.Remove(spriteAtlas, packables);

        List<Sprite> sprites = new List<Sprite>();
        string[] files = Directory.GetFiles(Path.GetDirectoryName(assetPath), "*.png");
        foreach (string file in files)
        {
            Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(file);
            sprites.Add(sprite);
        }

        SpriteAtlasExtensions.Add(spriteAtlas, sprites.ToArray());

        SpriteAtlasPackingSettings setting = spriteAtlas.GetPackingSettings();
        setting.enableTightPacking = false;
        SpriteAtlasExtensions.SetPackingSettings(spriteAtlas, setting);
#else
        string filePath = Path.GetDirectoryName(fileName);
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }

        Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);
        if (sprite)
        {
            GameObject spriteGo = new GameObject(sprite.name);
            if (spriteGo)
            {
                SpriteRenderer render = spriteGo.AddComponent<SpriteRenderer>();
                render.sprite = sprite;

                GeneratePrefab(spriteGo, filePath, sprite.name);
            }
        }
#endif

        AssetDatabase.Refresh();
    }
}
